//
//  LmExtension.swift
//  LMDevelopmentTool
//
//  Created by LaiMing on 2021/12/2.
//

import Foundation
import UIKit



public extension Array where Element: Equatable {
    
    /// 比对数组内容是否完全相等
    /// - Parameter compareArray: 需要比对的数组
    /// - Returns: 是否完全相等
    mutating func lmCompareArrayIsMatch(_ compareArray:[Element]) -> Bool where Element == Element, Element : Equatable {

        if self.count != compareArray.count {
            return false
        }
        
        
        var result:Bool = true
        
        for i in 0 ..< self.count {
            
            if self[i] != compareArray[i] {
                result = false
                break
            }
        }
        
        return result
    }

}





public extension UIButton {
    
    /// 定义button相对label的位置
     enum LMButtonImagePosition {
        case top          //图片在上，文字在下，垂直居中对齐
        case bottom       //图片在下，文字在上，垂直居中对齐
        case left         //图片在左，文字在右，水平居中对齐
        case right        //图片在右，文字在左，水平居中对齐
    }
    
    /// - Description 设置Button图片的位置
    /// - Parameters:
    ///   - style: 图片位置
    ///   - spacing: 按钮图片与文字之间的间隔
    public func lmImagePosition(style: LMButtonImagePosition, spacing: CGFloat) {
        //得到imageView和titleLabel的宽高
        let imageWidth = self.imageView?.frame.size.width
        let imageHeight = self.imageView?.frame.size.height
        
        var labelWidth: CGFloat! = 0.0
        var labelHeight: CGFloat! = 0.0
        
        labelWidth = self.titleLabel?.intrinsicContentSize.width
        labelHeight = self.titleLabel?.intrinsicContentSize.height
        
        //初始化imageEdgeInsets和labelEdgeInsets
        var imageEdgeInsets = UIEdgeInsets.zero
        var labelEdgeInsets = UIEdgeInsets.zero
        
        //根据style和space得到imageEdgeInsets和labelEdgeInsets的值
        switch style {
        case .top:
            //上 左 下 右
            imageEdgeInsets = UIEdgeInsets(top: -labelHeight-spacing/2, left: 0, bottom: 0, right: -labelWidth)
            labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth!, bottom: -imageHeight!-spacing/2, right: 0)
            break;
            
        case .left:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing/2, bottom: 0, right: spacing)
            labelEdgeInsets = UIEdgeInsets(top: 0, left: spacing/2, bottom: 0, right: -spacing/2)
            break;
            
        case .bottom:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -labelHeight!-spacing/2, right: -labelWidth)
            labelEdgeInsets = UIEdgeInsets(top: -imageHeight!-spacing/2, left: -imageWidth!, bottom: 0, right: 0)
            break;
            
        case .right:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: labelWidth+spacing/2, bottom: 0, right: -labelWidth-spacing/2)
            labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth!-spacing/2, bottom: 0, right: imageWidth!+spacing/2)
            break;
            
        }
        
        self.titleEdgeInsets = labelEdgeInsets
        self.imageEdgeInsets = imageEdgeInsets
    }

}




public extension UIImage {
    
    /// 图片加水印
    ///
    /// - Parameters:
    ///   - text: 水印完整文字
    ///   - textColor: 文字颜色
    ///   - textFont: 文字大小
    ///   - suffixText: 尾缀文字(如果是nil可以不传)
    ///   - suffixFont: 尾缀文字大小(如果是nil可以不传)
    ///   - suffixColor: 尾缀文字颜色(如果是nil可以不传)
    /// - Returns: 水印图片
    public func lmDrawTextInImage(text: String, textColor: UIColor, textFont: UIFont,suffixText: String?, suffixFont: UIFont?, suffixColor: UIColor?) -> UIImage {
        // 开启和原图一样大小的上下文（保证图片不模糊的方法）
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        
        // 图形重绘
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        
        var suffixAttr: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor:textColor, NSAttributedString.Key.font:textFont]
        let attrS = NSMutableAttributedString(string: text, attributes: suffixAttr)
        
        // 添加后缀的属性字符串
        if let suffixStr = suffixText {
            let range = NSRange(location: text.count - suffixStr.count, length: suffixStr.count)
            if suffixFont != nil {
                suffixAttr[NSAttributedString.Key.font] = suffixFont
            }
            
            if suffixColor != nil {
                suffixAttr[NSAttributedString.Key.foregroundColor] = suffixColor
            }
            attrS.addAttributes(suffixAttr, range: range)
        }
        
        // 文字属性
        let size =  attrS.size()
        let x = (self.size.width - size.width) / 2
        let y = (self.size.height - size.height) / 2
        
        // 绘制文字
        attrS.draw(in: CGRect(x: x, y: y, width: size.width, height: size.height))
        // 从当前上下文获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    
    /// 等比率缩放
    /// - Parameter scaleSize: 比例值
    /// - Returns: <#description#>
    public func lmScaleImage(scaleSize: CGFloat )-> UIImage  {
         
         let reSize = CGSize.init(width: size.width * scaleSize,
                                  height: size.height * scaleSize)
         
         return reSizeImage(reSize: reSize)
     }

    ///  重设图片大小
    /// - Parameter reSize: 大小
    /// - Returns: <#description#>
    private func reSizeImage(reSize: CGSize )-> UIImage  {
         
         //UIGraphicsBeginImageContext(reSize);
         UIGraphicsBeginImageContextWithOptions (reSize, false , UIScreen.main.scale)
         
         self.draw(in: CGRect.init(x: 0,
                                   y: 0,
                                   width: reSize.width,
                                   height: reSize.height))
         
//         self.drawInRect( CGRectMake (0, 0, reSize.width, reSize.height));
         let reSizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
         
         UIGraphicsEndImageContext ()
         
         return reSizeImage
     }
    
}




extension UITableView {
    
    /// 获取最大高度
    /// - Parameters:
    ///   - maxRowCount: 最大row的count
    ///   - maxSectionCount: 最大section的count，为0表示所有
    public func lmGetMaxHeight(with maxRowCount: Int, maxSectionCount: Int = 0) -> CGFloat {
        var sectionCount = maxSectionCount
        if maxSectionCount >= numberOfSections || maxSectionCount <= 0 {
            sectionCount = numberOfSections
        }
        var maxHeight: CGFloat = tableHeaderView?.frame.size.height ?? 0;
        for sectionIndex in 0..<sectionCount {
            var rowCount = numberOfRows(inSection: sectionIndex)
            if (rowCount > maxRowCount) {
                rowCount = maxRowCount;
            }
            
            maxHeight += delegate?.tableView?(self, heightForHeaderInSection: sectionCount) ?? 0
            for rowIndex in 0..<rowCount {
                maxHeight += delegate?.tableView?(self, heightForRowAt: IndexPath(row: rowIndex, section: sectionIndex)) ?? 0
                
            }
        }
        return maxHeight;
    }
    
    
    /// 获取指定高度的tableView image(截图用)
    /// - Parameter maxHeight: 最大高度(使用lmGetMaxHeight函数获得)
    public func lmGenerateTableViewImage(with maxHeight: CGFloat) -> UIImage? {
        var viewImage: UIImage?
        
        let savedContentOffset = contentOffset
        let savedFrame = frame
        
        let imageHeight = maxHeight > 0 ? maxHeight :contentSize.height
        var screensInTable = 0
        
        if (frame.size.height != 0) {
            screensInTable = Int(ceil(imageHeight / frame.size.height))
        }
        
        let sectionNum = numberOfSections
//        autoreleasepool {
            let imageSize = CGSize(width: frame.size.width, height: maxHeight)
            UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale)
            
            frame = CGRect(x: 0, y: 0, width: contentSize.width, height: imageHeight)
            
            let oldBounds = layer.bounds
            
        
            if #available(iOS 15, *) {
                //iOS 15 系统截屏需要改变tableview 的bounds
                layer.bounds = CGRect(x: oldBounds.origin.x,
                                                 y: oldBounds.origin.y,
                                                 width: contentSize.width,
                                                 height: contentSize.height)
                
                //偏移量归零
                contentOffset = CGPoint.zero
                //frame变为contentSize
                frame = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height)
            }
            
            
            for i in 0..<screensInTable {
                let contentOffset = CGPoint(x: CGFloat(0), y: CGFloat(i) * frame.size.height)
                setContentOffset(contentOffset, animated: false)
                
                // 隐藏应该移出屏幕的sectionHeader
                if (style == .plain) {
                    for i in 0..<sectionNum {
                        let headerRect = rect(forSection: i)
                        if (headerRect.origin.y < contentOffset.y) {
                            setupHeaderView(with: i, true)
                        }
                    }
                }
                if let context = UIGraphicsGetCurrentContext() {
                    layer.render(in: context)
                }
            }
//        }
        
        if #available(iOS 15, *) {
            layer.bounds = oldBounds
        }
        
        viewImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        if (style == .plain) {
            for i in 0..<sectionNum {
                setupHeaderView(with: i, false)
            }
        }
        
        frame = savedFrame
        setContentOffset(savedContentOffset, animated: false)
        return viewImage
    }
    
    /// 设置HeaderView的显示隐藏
    /// - Parameters:
    ///   - section: header所在的section
    ///   - isHidden: 是否隐藏
    private func setupHeaderView(with section: Int, _ isHidden: Bool) {
        
        var headerView1 = headerView(forSection: section)
        
        if nil == headerView {
            headerView1 = delegate?.tableView?(self, viewForHeaderInSection: section) as? UITableViewHeaderFooterView
        }
        headerView1?.isHidden = isHidden
    }
}
